<template>
  <!--  预调拨、调拨确认、闲置、报废、移交操作界面-->

  <a-card :bordered="false">
    <div v-if="+pageType !== 1 && +pageType !== 2" style="margin-bottom: 12px">
      <b>{{ title }}</b>
    </div>
    <a-row class="m-top" v-if="+pageType === 1" style="height: 5vh">
      <a-col span="2">待用项目:</a-col>
      <a-col span="5">
        <orgTreeSelect
            key="preAllotProjectName"
            :auto-selected="false"
            style="width: 15vw"
            is-maintenance
            allow-clear
            :isNeedAuth="false"
            :isHasChildren="false"
            :is-show-project-status="true"
            :is-search-page="true"
            :is-query-projec-detail="false"
            :check-strictly="false"
            placeholder="待用项目"
            :need-tags="[]"
            :value="{_checked: form.preAllotProjectId }"
            @select="selectPreOrg"
        ></orgTreeSelect>
      </a-col>
    </a-row>
    <a-row class="m-top" v-if="+pageType === 2" style="height: 5vh">
      <a-col span="2">使用项目:</a-col>
      <a-col span="5">
        <orgTreeSelect
            key="currentProjectName"
            :auto-selected="false"
            :isNeedAuth="false"
            style="width: 15vw"
            is-maintenance
            allow-clear
            :isHasChildren="false"
            :is-show-project-status="true"
            :is-search-page="true"
            :is-query-projec-detail="false"
            :check-strictly="false"
            placeholder="使用项目"
            :need-tags="[]"
            :value="{_checked: preAllotProjectInfo.preAllotProjectId }"
            @select="selectCurrentOrg"
        ></orgTreeSelect>
      </a-col>
    </a-row>

    <b-table
        class="m-table"
        ref="table"
        size="default"
        :scroll="{x:'2400px',y: '600px'}"
        :out-selected-row-keys.sync="outSelectedRowKeys"
        :rowKey="record => record.id"
        :columns="_tabColumnsManage"
        :request="loadData"
        :selectConfig="{use: true, type: 'checkbox',rowKey: 'id' }"
        :alert="true"
        show-size-changer
        show-quick-jumper
        :show-page="false"
    >
      <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
      <span slot="assetNumber" slot-scope="text, record, index">{{ record.ownerProjectNum + '-' + text }}</span>
      <span slot="discardTime" slot-scope="text, record">{{ formatTime(record.discardTime) }}</span>
      <span slot="allotTime" slot-scope="text, record">{{ formatTime(record.allotTime) }}</span>
      <span slot="enterTime" slot-scope="text, record">{{ formatTime(record.enterTime) }}</span>
      <template
          slot="assetStatus"
          slot-scope="key, record"
      >
        {{ mapAssetStatus(key) }}
      </template>
      <template
          slot="assetCatalogue"
          slot-scope="key, record"
      >
        {{ mapAssetCatalogue(key) }}
      </template>
      <template
          slot="buyCatalogue"
          slot-scope="key, record"
      >
        {{ mapBuyCatalogue(key) }}
      </template>

      <span slot="operation" slot-scope="text, record">
                <a @click="toDetail(record)">查看</a>
      </span>

      <!--  footer-->

      <a-form-model ref="form" class="importCom" slot="footer" layout="inline">
        <a-row type="flex" justify="space-between">
          <!--  预调拨1-->
          <a-col class="placeholder" span="5" v-if="pageType === 1">
            <!--   占位没啥用为了使后面的按钮【提交、取消、去除】位置不错位-->
          </a-col>

          <a-col span="6" v-if="pageType === 2">
            <a-form-model-item prop="allotTime" label="调拨时间"
                               :labelCol="{style: 'width: 35%'}"
                               :wrapperCol="{style: 'width: 65%'}">
              <a-date-picker v-model="form.allotTime" format="YYYY-MM-DD" value-format="YYYY-MM-DD 00:00:00"
                             autocomplete="off"
                             placeholder="默认当前时间"/>
            </a-form-model-item>
          </a-col>
          <a-col span="4" v-if="pageType === 2">
            <a-form-model-item prop="keeperId" label="保管人" :labelCol="{style: 'width: 35%'}"
                               :wrapperCol="{style: 'width: 65%'}">
              <a-input-search v-model="form.keeperName" :placeholder="form.keeperName || '默认为使用项目的总工'"
                              @click="()=> modal.visible = true"></a-input-search>
              <SelectPerson
                  :visible.sync="modal.visible"
                  mode="single"
                  :need-data="modal.visible"
                  :org-id="modal.orgId"
                  :list.sync="modal.list"
                  @getSelectPerson="setSelectPerson($event)"
              />
            </a-form-model-item>
          </a-col>
          <a-col span="4" v-if="pageType === 2">
            <a-form-model-item label="验收单" prop="checkFile" :labelCol="{style: 'width: 55%'}"
                               :wrapperCol="{style: 'width: 45%'}">
              <l-table count="1"
                       :upload-arrys.sync="form.checkFile"
                       business-code="AM02"/>
            </a-form-model-item>
          </a-col>

          <!--  设备闲置 3-->
          <a-col span="4" v-if="pageType === 3">
            <a-form-model-item prop="destroyTime" label="拆除时间" :labelCol="{style: 'width: 35%'}"
                               :wrapperCol="{style: 'width: 65%'}">
              <a-date-picker v-model="form.destroyTime" format="YYYY-MM-DD" value-format="YYYY-MM-DD 00:00:00"
                             autocomplete="off"
                             placeholder="默认当前时间"/>
            </a-form-model-item>
          </a-col>
          <a-col span="7" v-if="pageType === 3">
            <a-form-model-item label="拆除验收单" prop="receiveFile" :labelCol="{style: 'width: 55%'}"
                               :wrapperCol="{style: 'width: 45%'}">
              <l-table count="1"
                       :upload-arrys.sync="form.receiveFile"
                       business-code="AM03"/>
            </a-form-model-item>
          </a-col>
          <!--  报废、丢失4-->
          <a-col span="5" v-if="pageType === 4">
            <a-form-model-item prop="discardTime" label="报废/丢失时间"
                               :labelCol="{span:2}"
                               :wrapperCol="{span:4}">
              <a-date-picker v-model="form.discardTime" format="YYYY-MM-DD" value-format="YYYY-MM-DD 00:00:00"
                             autocomplete="off"
                             placeholder="默认当前时间"/>
            </a-form-model-item>
          </a-col>
          <a-col span="6" v-if="pageType === 4">
            <a-form-model-item prop="discardType" label="报废/丢失"
                               :labelCol="{style:'width:50%'}"
                               :wrapperCol="{style:'width:50%'}">
              <a-select v-model="form.discardType" style="width:7vw" placeholder="请选择类型" allowClear>
                <a-select-option value="3">
                  报废
                </a-select-option>
                <a-select-option value="4">
                  丢失
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col span="8" v-if="pageType === 4" pull="2">
            <a-form-model-item label="报废/丢失确认单"
                               style="width:100%"
                               prop="confirmFile"
                               :labelCol="{span: 2}"
                               :wrapperCol="{span:7}">
              <l-table count="1"
                       :upload-arrys.sync="form.confirmFile"
                       business-code="AM04"/>
            </a-form-model-item>
          </a-col>

          <!--  移交5-->
          <a-col span="4" v-if="pageType === 5">
            <a-form-model-item prop="keeperId" label="保管人" :labelCol="{style: 'width: 30%'}"
                               :wrapperCol="{style: 'width: 70%'}">
              <a-input-search v-model="form.keeperName" placeholder="请选择要移交的保管人" style="width:10vw"
                              @click="()=> modal.visible = true"></a-input-search>
              <SelectPerson
                  :visible.sync="modal.visible"
                  mode="single"
                  title="请选择要移交的保管人"
                  :org-id="modal.orgId"
                  :list.sync="modal.list"
                  @getSelectPerson="setSelectPerson($event)"
              />
            </a-form-model-item>
          </a-col>
          <a-col span="5" v-if="pageType === 5">
            <a-form-model-item prop="keeperTel" label="保管人电话" :labelCol="{style: 'width: 35%'}"
                               :wrapperCol="{style: 'width: 65%'}">
              <a-input v-model="form.keeperPhone"
                       placeholder="保管人电话" type="text"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col span="7" v-if="pageType === 5">
            <a-form-model-item label="验收单"
                               prop="receiveFile"
                               :labelCol="{style: 'width: 55%'}"
                               :wrapperCol="{style: 'width: 45%'}">
              <l-table count="1"
                       :upload-arrys.sync="form.receiveFile"
                       business-code="AM02"/>
            </a-form-model-item>
          </a-col>


          <!--  按钮-->
          <a-col span="5" push="1">
            <a-form-model-item>
              <div style="display:flex">
                <a-button type="primary"
                          style="margin-right: 12px"
                          :disabled="outSelectedRowKeys.length===0"
                          @click="handleRemove">去除
                </a-button>
                <a-button type="primary" @click="submit" :loading="loadingSubmit">提交</a-button>
                <a-button style="margin-left: 10px" @click="cancel">取消</a-button>
              </div>
            </a-form-model-item>
          </a-col>
        </a-row>

      </a-form-model>
    </b-table>
  </a-card>

</template>
<script>
import {mapAssetCatalogue, mapAssetStatus, mapBuyCatalogue, tabColumnsManage} from '../model'
import {getProjectsList} from "@/api/project/projects";
import SelectPerson from "@/components/Select/SelectPerson.vue";
import moment from "moment/moment";
import {handleAssetManage, getKeeperInfo} from "@/api/material/assets/assetManage";
import orgTreeSelect from "@/components/OrgTreeSelect"

export default {
  name: 'AssetAction',
  components: {SelectPerson, orgTreeSelect},
  data() {
    return {
      tabColumnsManage,
      outSelectedRowKeys: [],
      tableData: [],
      loadingSubmit: false,
      pageType: undefined,
      form: {
        checkFile: [],
        receiveFile: [],
        confirmFile: [],

        preAllotProjectId: undefined,
        preAllotProjectName: undefined,

        currentProjectId: undefined,
        currentProjectName: undefined,

        keeperId: undefined,
        keeperPhone: undefined,
        keeperName: undefined,

        destroyTime: this.formatTime2(new Date()),
        allotTime: this.formatTime2(new Date()),

        discardTime: this.formatTime2(new Date()),
        discardType: undefined
      },
      modal: {
        visible: false,
        orgId: '06bcbdacb4374523bdaf66586c45f749',
        list: []
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        return {
          code: 200,
          data: this.tableData || [],
          totalSize: this.tableData?.length || 0,
        }
      },
    }
  },
  methods: {
    formatTime(time) {
      return time ? moment(time).format('YYYY-MM-DD') : '-'
    },
    formatTime2(time) {
      return time ? moment(time).format('YYYY-MM-DD HH:mm:ss') : '-'
    },
    mapAssetCatalogue,
    mapAssetStatus,
    mapBuyCatalogue,
    selectPreOrg(val) {
      if (val && val.length) {
        const lastValue = val[val.length - 1]
        if (lastValue.tageCode === 'PD' && lastValue.projectId) {
          this.form.preAllotProjectId = lastValue.projectId
          this.form.preAllotProjectName = lastValue.projectName
        } else {
          this.$message.warn("请选择项目，而不是分公司")
        }
      }
    },
    selectCurrentOrg(val) {
      if (val && val.length) {
        const lastValue = val[val.length - 1]
        if (lastValue.tageCode === 'PD' && lastValue.projectId) {
          this.form.currentProjectId = lastValue.projectId
          this.form.currentProjectName = lastValue.projectName
        } else {
          this.$message.warn("请选择项目，而不是分公司")
        }
      }
    },
    toDetail(item) {
      this.$router.push({
        name: 'AssetManageEdit',
        params: item,
        query: {
          id: item.id,
          isEdit: 0
        }
      })
    },
    setSelectPerson(selected) {
      let selectPerson = selected[0]
      this.form.keeperId = selectPerson.userId
      this.form.keeperName = selectPerson.name
      this.form.keeperPhone = selectPerson.phone
    },
    handleRemove() {
      this.tableData = this.tableData.filter((item) => !this.outSelectedRowKeys.includes(item.id))
      this.$refs.table.refresh(false)
    },
    cancel() {
      this.$multiTab.closeIframe(this.$route.path)
    },
    submit() {
      if (this.tableData.length === 0) {
        this.$message.success("资产列表为空!")
        return
      }
      let param = {
        ids: this.tableData.map(item => item.id),
        parameter: {}
      }

      if (this.pageType === 1) { //预调拨
        if (!this.form.preAllotProjectId || this.form.preAllotProjectId === '') {
          this.$message.warn("请选择预待用项目!")
          return
        }
        param.parameter = {
          preAllotProjectName: this.form.preAllotProjectName,
          preAllotProjectId: this.form.preAllotProjectId
        }
      } else if (this.pageType === 2) {  //调拨确认
        // let projectId = this.form.currentProjectId || this.preAllotProjectInfo.preAllotProjectId
        // let projectName = this.form.currentProjectName || this.preAllotProjectInfo.preAllotProjectName
        // if (!this.form.currentProjectId || this.form.currentProjectName === '') {
        //   this.$message.warn("请选择使用项目!")
        //   return
        // }

        if (this.form.checkFile.length === 0) {
          this.$message.warn("请上传验收单!")
          return
        }
        if (!this.form.keeperId || this.form.keeperId === '') {
          this.$message.warn("请选择保管人!")
          return
        }
        param.parameter = {
          currentProjectId: this.form.currentProjectId || this.preAllotProjectInfo.preAllotProjectId,
          currentProjectName: this.form.currentProjectName || this.preAllotProjectInfo.preAllotProjectName,
          fileId: this.form.checkFile.map((item) => item.commonId),
          allotTime: this.form.allotTime,
          keeperId: this.form.keeperId,
          keeperName: this.form.keeperName,
          keeperPhone: this.form.keeperPhone,
        }
      } else if (this.pageType === 3) { //设备闲置
        if (this.form.receiveFile.length === 0) {
          this.$message.warn("请上传拆除验收单!")
          return
        }
        param.parameter = {
          fileId: this.form.receiveFile.map((item) => item.commonId),
          idleTime: this.form.destroyTime
        }
      } else if (this.pageType === 4) { //报废/丢失
        if (!this.form.discardType || this.form.discardType === '') {
          this.$message.warn("请选择报废/丢失类型!")
          return
        }
        // if( this.form.confirmFile.length === 0){ //非必传
        //   this.$message.warn("请上传验收附件!")
        //   return
        // }
        param.parameter = {
          discardType: this.form.discardType,
          discardTime: this.form.discardTime,
          fileId: this.form.confirmFile.map((item) => item.commonId)
        }
      } else if (this.pageType === 5) { //保管移交
        if (!this.form.keeperId || this.form.keeperId === '') {
          this.$message.warn("请选择移交保管人!")
          return
        }
        param.parameter = {
          keeperId: this.form.keeperId,
          keeperName: this.form.keeperName,
          keeperPhone: this.form.keeperPhone,
          fileId: this.form.receiveFile.map((item) => item.commonId)
        }
      }
      param.parameter.actionType = this.pageType
      this.loadingSubmit = true
      handleAssetManage(param)
          .then((res) => {
            this.loadingSubmit = false
            if (res.code === '0') {
              this.$message.success("操作成功!")
              this.cancel()
            }
          })
          .catch((e) => {
            this.loadingSubmit = false
          })
    }
  },
  activated() {
    //string -> number
    this.pageType = +this.$route.query.type
    this.tableData = this.$route.params.list || []
    if (this.$route.params.list) {
      this.$refs.table.refresh(true)
    }
  },
  computed: {
    title: function () {
      return this.$route.query.title
    },
    preAllotProjectInfo: function () {
      let preAllotProjectInfos = this.tableData.map((item) => {
        return {
          preAllotProjectId: item.preAllotProjectId,
          preAllotProjectName: item.preAllotProjectName,
          keeperId: item.keeperId,
          keeperName: item.keeperName,
          keeperPhone: item.keeperPhone
        }
      }) || [];
      if(!preAllotProjectInfos[0]){
        return
      }
      this.form.currentProjectId = preAllotProjectInfos[0].preAllotProjectId
      this.form.currentProjectName = preAllotProjectInfos[0].preAllotProjectName
      return preAllotProjectInfos[0] || {}
    },
    _tabColumnsManage: function () {
      return this.tabColumnsManage
    }

  },
  watch: {
    'form.currentProjectId': {
      handler: function (newVal, val) {
        if(!newVal){
          return
        }
        getKeeperInfo({projectId: newVal}).then(res => {
          console.log('总工信息=', res)
          if (res.code === '0' && res.data.length > 0) {
            let p = res.data[0]
            if(p){
              this.form.keeperId = p.id
              this.form.keeperPhone = p.phone
              this.form.keeperName = p.userName
            }
          }
        })
      }
    }
  },
  beforeRouteEnter(to, from, next) {
    let type = +to.query.type
    if (type === 1) {
      to.meta.title = '资产管理-预调拨'
    } else if (type === 2) {
      to.meta.title = '资产管理-调拨确认'
    } else if (type === 3) {
      to.meta.title = '资产管理-设备闲置'
    } else if (type === 4) {
      to.meta.title = '资产管理-报废/丢失'
    } else if (type === 5) {
      to.meta.title = '资产管理-保管移交'
    }
    next()
  }
}
</script>
<style scoped lang="less">
.main /deep/ .ant-card {
  height: 90%;
}

/deep/ .ant-input {
  border-color: #e4ac0b;
  background-color: #fff9e8;
}



.m-top /deep/ .treeOrgBox .searchIcon {
  top: 7px;
}
/deep/ .m-top .ant-col-2{
  width: 4.3%
}
/deep/ .ant-card-body table{
  margin-left: 0;
  margin-right: 0;
}

/deep/ .ant-table-row .ant-table-row-cell-break-word{
  overflow:hidden;
  text-overflow:ellipsis;//溢出部分用省略号代替
  -webkit-line-clamp:1; //设置文本显示1行，想要几行把1替换掉就行
  display: table-cell !important; //将对象作为弹性伸缩盒子模型显示;

  white-space:nowrap;
  word-break: break-all;
}
/deep/ .ant-table-row-cell-last{
  width: 175px;
}

.m-table /deep/ .ant-table-body {
  min-height: 55vh;
}

/deep/ .m-table .ant-table-tbody > tr > td {
  height: 50px;
}
//调整head行属性
/deep/ .m-table .ant-table-thead > tr > th {
  height: 50px;

}
</style>